from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session, joinedload
from sqlalchemy import desc, func
from app.database import get_db
from app.models.user import User
from app.models.spot import Spot
from app.models.favorite import Favorite
from app.models.order import Order
from app.core.auth import get_current_user
from pydantic import BaseModel, EmailStr

router = APIRouter()

class ProfileUpdate(BaseModel):
    username: str | None = None
    email: EmailStr | None = None
    name: str | None = None
    phone: str | None = None
    address: str | None = None

@router.get("/favorites")
def get_favorites(
    db: Session = Depends(get_db),
    current_user = Depends(get_current_user)
):
    """获取用户的收藏列表"""
    favorites = (
        db.query(Favorite)
        .filter(Favorite.user_id == current_user.id)
        .join(Spot)
        .options(joinedload(Favorite.spot))
        .order_by(desc(Favorite.created_at))  # 按创建时间倒序排序
        .all()
    )
    
    return [
        {
            "id": fav.id,
            "created_at": fav.created_at,
            "spot": {
                "id": fav.spot.id,
                "name": fav.spot.name,
                "description": fav.spot.description,
                "price": fav.spot.price,
                "images": fav.spot.images,
                "type": fav.spot.type
            }
        }
        for fav in favorites
    ]

@router.get("/order-summary")
async def get_order_summary(
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """获取用户订单统计信息"""
    stats = (
        db.query(
            func.count(Order.id).label('total_orders'),
            func.sum(Order.total_price).label('total_spent')
        )
        .filter(Order.user_id == current_user.id)
        .first()
    )

    recent_orders = (
        db.query(Order)
        .filter(Order.user_id == current_user.id)
        .join(Order.spot)
        .order_by(desc(Order.visit_date))
        .limit(5)
        .all()
    )

    return {
        "total_orders": stats[0] or 0,
        "total_spent": float(stats[1] or 0),
        "recent_spots": [order.spot.name for order in recent_orders]
    }

@router.put("/profile")
def update_profile(
    profile: ProfileUpdate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """更新用户资料"""
    # 检查用户名是否已被使用
    if profile.username and profile.username != current_user.username:
        existing_user = db.query(User).filter(User.username == profile.username).first()
        if existing_user:
            raise HTTPException(status_code=400, detail="用户名已被使用")

    # 检查邮箱是否已被使用
    if profile.email and profile.email != current_user.email:
        existing_user = db.query(User).filter(User.email == profile.email).first()
        if existing_user:
            raise HTTPException(status_code=400, detail="邮箱已被使用")

    # 更新用户信息
    for key, value in profile.dict(exclude_unset=True).items():
        setattr(current_user, key, value)
    
    db.commit()
    db.refresh(current_user)
    
    return {
        "id": current_user.id,
        "username": current_user.username,
        "email": current_user.email,
        "name": current_user.name,
        "phone": current_user.phone,
        "address": current_user.address
    } 